from PyQt5.QtWidgets import QAbstractItemView,QStyleOptionViewItem, QWidget, QApplication, QTableWidget, QTableWidgetItem, QItemEditorCreatorBase, QDateTimeEdit, QItemEditorFactory, QStyledItemDelegate
from PyQt5.QtCore import  QVariant, QDateTime, QObject,Qt,QModelIndex,pyqtSlot,pyqtSignal,QAbstractItemModel
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QFileDialog
from PyQt5 import QtWidgets
import sys
import os
from PyQt5.QtGui import  QBrush, QPixmap, QColor, QPainter,QIcon,QPolygon
import logging
from delegates import PixmapDialogDelegate
class DecimalTableWidgetItem(QtWidgets.QTableWidgetItem):
    def __init__(self, text):
        super().__init__(text)

    def __lt__(self, other):
        return float(self.text()) < float(other.text())

    def setData(self, role, value):
        if role != 0:
            return
        try:
            float(value)
            super().setData(role, value)
        except ValueError:
            return
class MyTable(QTableWidget):
    def __init__(self,rows,cols,parent):
        super().__init__(rows,cols,parent)
        self.cellBottomRight=False
        self.leftbuttonDown=False
    def paintEvent(self,e):
        super().paintEvent(e)
        painter=QPainter(self.viewport())
        pen = painter.pen();
        pen.setWidth(1);
        i=0
        # print(dir(self))#selectionModel
        selections = self.selectionModel()
        list1 = selections.selectedIndexes()
        for modelIndex in list1:
            #QRect类提供各种矩形坐标，绘制线跟点的时候需要用到坐标
            rect = self.visualRect(modelIndex);
            tmpRect = rect;
 
            #如果是选中状态 并且在选择公式状态
            # print(self.item(i,j).data(Qt.EditRole),dir(self.item(i,j)))
            # if (self.item(i,j).isSelected()):
            pix=modelIndex.data(Qt.EditRole)
            if isinstance(pix,QPixmap):
                painter.drawPixmap(tmpRect,pix);
            # value =self.item(i,j).data(index)
            #给选中单元格进行画线画点
            dashes=[]
            penXu = painter.pen();
            #设置画笔宽度
            penXu.setWidth(2);
            color=QColor();
            #设置画笔颜色
            color.setRgb(31,187,125);
            penXu.setColor(color);
            painter.setPen(penXu);
            #绘制单元格四周的线
            painter.drawRect(tmpRect);
            #绘制单元格右下角点
            penXu.setWidth(6);
            painter.setPen(penXu);
            painter.drawPoint(tmpRect.x()+tmpRect.width() -3,tmpRect.y()+tmpRect.height()-3);
        self.viewport().update()
    #鼠标移动事件
    def mouseMoveEvent(self,event):
        #获取鼠标位置信息
        if not self.cellBottomRight:
            mousePos =event.pos();
            #获取所有选中单元格
            logging.info(self.cellBottomRight)
            itemList = self.selectedItems();
            #没有选中单元格 就退出
            if len(itemList) <= 0:
                return;
            modelIndex = self.indexFromItem(itemList[len(itemList)-1]);
            #获取最后一个选中的单元格的QRect，用来判断是否鼠标位置是否在右下角区域
            rect = self.visualRect(modelIndex);
            logging.info([mousePos,rect])
            #判断是否在我们规定的区域，或者是按下模式，isClick是按下模式标志
            # print(dir(mousePos))
            if((mousePos.x() >= (rect.x()+rect.width() -7) and mousePos.x() <= (rect.x()+rect.width())
                and mousePos.y() >= (rect.y()+rect.height()-7) and mousePos.y() <= (rect.y()+rect.height()))):
                logging.info("right bottom")
                #设置鼠标在右下角区域样式
                self.setCursor(Qt.CrossCursor);
                #在右下角区域
                self.cellBottomRight = True;
        super().mouseMoveEvent(event);
        #鼠标点击事件
    def mousePressEvent(self,event):
        if(event.button()==Qt.LeftButton):
            self.leftbuttonDown = True;
            self.setCursor(Qt.SizeAllCursor);
        else:
            self.leftbuttonDown = False;
            self.setCursor(Qt.ArrowCursor);
        super().mousePressEvent(event);#提交鼠标给控件
    def mouseReleaseEvent(self,ev):
        if self.leftbuttonDown and self.cellBottomRight:
            itemList = self.selectedItems();
            if len(itemList)>0:
                first=itemList[0].text()
                for item in itemList[1:]:
                    item.setText(first)
        self.leftbuttonDown = False;
        self.cellBottomRight = False;
        self.setCursor(Qt.ArrowCursor);
        super().mouseReleaseEvent(ev)
class DateTimeEditorCreator(QItemEditorCreatorBase):
    """
    See gui/itemviews/qitemeditorfactory.cpp for implementations of
    createEditor() and valuePropertyName()
    """
    def __init__(self):
        QItemEditorCreatorBase.__init__(self)

    def createWidget(self, parent):
        wid = QDateTimeEdit(parent)
        wid.setCalendarPopup(True)
        wid.setFrame(False)
        return wid

    def valuePropertyName(self):
        return "dateTime"

def die():
    raise MyError("Oops")

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
def item_change(item):
        print(item)
        dir(item)
def main():
    app = QApplication(sys.argv)
    tableWidget =MyTable(12,3,None)# QTableWidget(12, 3)
    # tableWidget.itemChanged.connect(item_change)
    # tableWidget.setItemDelegate(QStyledItemDelegate())
    # tableWidget.itemDelegate().setItemEditorFactory(QItemEditorFactory())
    # tableWidget.itemDelegate().itemEditorFactory().registerEditor(QVariant.DateTime, DateTimeEditorCreator())
    # tableWidget.setItemDelegate(PixmapDelegate())
    tableWidget.setItemDelegate(PixmapDialogDelegate())
    # tableWidget.setItemDelegate(SpreadSheetDelegate())
    tableWidget.setEditTriggers(
                QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked)
    for row in range(10):
        for col in range(3):
            # date = QDateTime.currentDateTime()
            # string = str(row) + ',' + str(col)
            # item = QTableWidgetItem()
            # item.setData(Qt.DisplayRole, QVariant(date))
            # tableWidget.setItem(row, col, item)
            item = QTableWidgetItem();
            tableWidget.setItem(row, col, item)
            item.setData(Qt.DisplayRole,QPixmap("./images/star.png"));
    tableWidget.show()
    sys.exit(app.exec_())
if __name__=="__main__":
    main()